package com.dhcc.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javassist.expr.NewArray;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import sun.tools.tree.ThisExpression;

import com.dhcc.dto.MatialsSearchConditionDTO;
import com.dhcc.model.CouMat;
import com.dhcc.service.CouMatService;
import com.dhcc.utils.IPTimeStamp;
import com.dhcc.utils.LogUtil;
import com.dhcc.utils.Pager;

/**
 * 
 * 资料管理
 * 
 * @author zhangkairong
 *
 */
@Controller
@RequestMapping("/material")
public class CouMatController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private CouMatService couMatService;
	
	
	
	//TODO 查询课程 cotroller
//	public String queryConrse(){
//		
//		return "";
//	}
	@ResponseBody
	@RequestMapping(value = "/search",method = RequestMethod.POST)
	public String search(@RequestBody MatialsSearchConditionDTO dto){
		
		logger.debug("查询的条件是:{}",dto);
		
		
		return "";
	}
	
	
	
	
	@ResponseBody
	@RequestMapping(value = "/datchdelete",method = RequestMethod.POST)
	public String datchDelete(@RequestParam("arrIds[]") List<String> arrIds
			,HttpServletRequest request){
		
		logger.debug("删除数据的ids{}",arrIds);
		
		String[] ids = arrIds.toArray(new String[arrIds.size()]);
		logger.debug("list转化成字符串数据的ids{}",ids);
		StringBuilder bufferBuilder = new StringBuilder();
		
		for (int i = 0; i < ids.length; i++) {
			
			
			bufferBuilder.append(ids[i]).append(",");
		}
		bufferBuilder.deleteCharAt(bufferBuilder.length()-1);
		
		logger.debug("并接的字符串是:{}",bufferBuilder.toString());
		
		try {
			couMatService.datchDelete(bufferBuilder.toString());
		} catch (Exception e) {
			request.setAttribute("msg", "批量删除失败");
			logger.error(LogUtil.getTrace(e));
			return "error";
		}
		
		return "success";
	}
	
	@RequestMapping(value = "/{id}/delete",method = RequestMethod.GET)
	public String deleteOne(@PathVariable("id")long id ,
			@RequestParam(value="currentPage",defaultValue="1") int currentPage,
			HttpServletRequest request){
		
		logger.debug("删除的id是:{}" ,id);
		CouMat couMat = couMatService.get(id);
		String matUrl = couMat.getMatUrl();
		String realPath = request.getSession().getServletContext().getRealPath("/upload");
		
		String deleteFile = realPath + "/" + couMat.getMatUrl();
		
		File file = new File(deleteFile);
		
		if (file.exists()) {
			
			file.delete();
		}
		couMatService.delete(couMat);
		
		return "redirect:/material/list?currentPage=" + currentPage;
	}
	
	//添加
	@RequestMapping(value = "/add",method=RequestMethod.POST)
	public String add(CouMat couMat,@RequestParam("file")MultipartFile file
					,HttpServletRequest request,HttpServletResponse response
					,@RequestParam(value="currentPage",defaultValue="1") int currentPage){
		
		String realPath = request.getSession().getServletContext()
				.getRealPath("/upload");
		
		File pathFile = new File(realPath);
		if (!pathFile.exists()) {
			
			pathFile.mkdir();
		}
		IPTimeStamp ipTimeStamp = new IPTimeStamp();
		//获得新文件的名字
		String timeStamp = ipTimeStamp.getTimeStamp();
		
		//获得上传文件的后缀
		String ext = FilenameUtils.getExtension(file.getOriginalFilename());
		//并新文件的名称
		String newFilename = timeStamp + "." + ext;
		
		couMat.setMatUrl(newFilename);
		
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), 
					new File(realPath, newFilename));
		} catch (IOException e) {
			request.setAttribute("msg", "上传图片失败");
			return "error";
		}
		
		couMatService.save(couMat);
		
		logger.debug("上传文件的类型是:{}",file.getContentType());
		logger.debug("上传源文件文件的名称是:{}",file.getOriginalFilename());
		logger.debug("上传文件的大小是{}",file.getSize());
		
		logger.debug("上传保存文件文件的名称是:{}",newFilename);
		
		logger.debug("前台传到Controller的coumat的值是：{}" , couMat);
		
		return "redirect:/material/list?currentPage=" + currentPage;
	}
	
	
	
	@RequestMapping(value = "list",method = RequestMethod.GET)
	public String listMaterial(Model model,@RequestParam(value="currentPage",defaultValue="1") int currentPage){
		
		 Pager<CouMat> pager = couMatService.query(currentPage);
		
		model.addAttribute("pager", pager);
		
		if (pager.getList().size()==0&&currentPage!=1) {
			return "redirect:/material/list?currentPage=1";
		}
		
		
		
		return "material/list";
	}
	
	

}
